package com.panfeng.xcloud.gateway.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * 国际化功能ZuulFilter过滤器
 *
 * @author xiaobo
 * @date 2020-02-13
 */
//@Component
public class localeFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(ErrorFilter.class);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String language = request.getHeader("language");
        switch (language) {
            case "en":
                request.setAttribute("language", new Locale("en", "US"));
                break;
            case "ja":
                request.setAttribute("language", new Locale("ja", ""));
                break;
            case "ko":
                request.setAttribute("language", new Locale("ko", ""));
                break;
            case "zh-Hans":
                request.setAttribute("language", new Locale("zh", "CN"));
                break;
            case "zh-Hant":
                request.setAttribute("language", new Locale("zh", "TW"));
                break;
            default:
                request.setAttribute("language", new Locale("en", "US"));
                break;
        }
        return null;
    }

    /**
     * 返回逻辑统一处理
     *
     * @param ctx
     * @param errorResponse
     * @throws IOException
     */
    private void responseHandler(RequestContext ctx,
                                 String errorResponse) throws IOException {
        ctx.setSendZuulResponse(false);
        HttpServletResponse httpResponse = ctx.getResponse();
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.getWriter().write(errorResponse);
        ctx.setResponse(httpResponse);
    }

}
